const crypto = require('crypto')

exports.md5 = function (text) {
    const hash = crypto.createHash('md5')
    hash.update(text)
    return hash.digest('hex')
}

exports.randomBytes = function (size) {
    return crypto.randomBytes(size)
}

/**
 * 加密字符串
 * **/
exports.cipherText = function cipherText (content, algorithm, key, iv, outputEncoding) {
    const cipher = crypto.createCipheriv(algorithm, key, iv)
    const data = cipher.update(content, 'utf8', outputEncoding || 'base64')
    return data + cipher.final(outputEncoding || 'base64')
}

/**
 * 解密字符串
 * **/
exports.decipherText = function decipherText (encrypted, algorithm, key, iv, inputEncoding) {
    const decipher = crypto.createDecipheriv(algorithm, key, iv)
    const text = decipher.update(encrypted, inputEncoding, 'utf8')
    return text + decipher.final('utf8')
}

exports.isEmpty = function (v) {
    for (const k in v) {
        if (v[k] === undefined) return true
    }
    return false
}

exports.pickBy = function (data, fn = v => v !== undefined) {
    const data2 = {}
    for (const k in data) {
        if (fn(data[k], k)) {
            data2[k] = data[k]
        }
    }

    return data2
}

exports.pick = function (data, keys) {
    const data2 = {}
    if (keys.length === 0) return {}
    for (const k in data) {
        if (keys.indexOf(k) > -1) {
            data2[k] = data[k]
        }
    }

    return data2
}
